<?php

namespace app\common\model;

use app\admin\model\Githouse;
use app\admin\model\halt\Cate;
use think\Model;

class Serial extends Model
{
    // 表名
    protected $name = 'serial';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    
    // 追加属性
    protected $append = [
        'sendtime_text',
        'type_text',
        'dealer_text',
        'branch_text'
    ];


    public function getBranchTextAttr($value, $data)
    {
        if(!$data['branch_uid']) return '';
        $value = $value ? $value : $data['branch_uid'];
        return Githouse::get(['id'=>$data['branch_uid']])->gname;
    }

    public function getDealerTextAttr($value, $data)
    {
        if(!$data['dealer_uid']) return '';
        $value = $value ? $value : $data['dealer_uid'];
        return Agent::get(['id'=>$data['dealer_uid']])->agent_name;
    }

    public function getSendtimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['sendtime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setSendtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    public function getTypeList()
    {
        return array_column(collection(Cate::field('id,name')->select())->toArray(), 'name','id');
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['type'];
        $list = $this->getTypeList();
        $arr = explode(',',$value);
        foreach ($arr as $value)
        {
            $str[] = $list[$value] ?? '';
        }
        $str  = implode(',', $str);
        return  $str;
    }


}
